import _ from 'lodash';
import axios from 'axios';
import qs from 'qs';
import { config } from "./config.js";
import { ElLoading } from 'element-plus';
import app from '@/main.js'

const singleObject = new Object();
(function(single){
    const global = app.config.globalProperties;
    global['singleAlert'] = null;

    /**
     * 实现提示信息只弹出一次
     * @param message 消息内容
     * @param title 消息标题
     * @param options 提示信息的配置
     */
    single.singleAlert = function(message,title,options){
        if(global.singleAlert == null){
            if(options['beforeClose'] != null){
                const closeCallback = options['beforeClose'];
                options['beforeClose'] = function(action, instance, done){
                    global['singleAlert'] = null;
                    closeCallback();
                    done();
                }
            }else{
                options['beforeClose'] = function(action, instance, done){
                    global['singleAlert'] = null;
                    done();
                }
            }
            global['singleAlert'] = global.$alert(message,title,options);
        }else{
            return
        }
    }
})(singleObject)

const request = new Object();
(function (w) {
    const global = app.config.globalProperties;
    const loginError = function (res) {
        if (res.data.code == "0005" || res.data.code == "0006") {
            singleObject.singleAlert(res.data.message, '错误信息', {
                type: 'error',
                confirmButtonText: '确定',
                callback: action => {
                    localStorage.clear();
                    global.$router.push({path: "/", replace: true}).catch(function () { });
                },
                "show-close": false,
                "beforeClose": () => {}
            });
            return false;
        }
        return true;
    }

    /**
     * get请求
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     */
    const getRequest = function (url, errCallBack, callBack, isUseLoading) {
        this.url = url;
        this.errCallBack = errCallBack;
        this.callBack = callBack;
        this.isUseLoading = isUseLoading;
        this.init();
    };
    getRequest.prototype = {
        init: function () {
            var obj = this;

            let loading = null;
            if(this.isUseLoading){
                loading = ElLoading.service({ lock: true, text: '数据加载中...' });
            }
            let header = {
                
            };
            if(tool.cookieValue("XSRF-TOKEN")){
                header["X-XSRF-TOKEN"] = tool.cookieValue("XSRF-TOKEN");
            }
            if(tool.getLoginToken()){
                header["Login-Token"] = tool.getLoginToken();
            }

            axios({
                headers: header,
                url: obj.url,
                method: "GET"
            }).then(function (response) {
                if(loading){
                    loading.close();
                }
                if (!loginError(response)) {
                    return;
                }
                if (obj.callBack != null) {
                    obj.callBack(response.data);
                }
            }).catch(function (error) {
                if(loading){
                    loading.close();
                }
                if (obj.errCallBack != null) {
                    obj.errCallBack();
                } else {
                    singleObject.singleAlert("请求异常", "错误信息",{
                        confirmButtonText: '确定',
                        type: 'error'
                    });
                }
            });
        }
    };
    w.getRequest = getRequest;

    /**
     * application/x-www-form-urlencoded; charset=UTF-8 
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     */
    const formRequest = function (url, data, errCallBack, callBack, isUseLoading) {
        this.url = url;
        this.data = data;
        this.errCallBack = errCallBack;
        this.callBack = callBack;
        this.isUseLoading = isUseLoading;
        this.init();
    };
    formRequest.prototype = {
        init: function () {
            var obj = this;

            let loading = null;
            if(this.isUseLoading){
                loading = ElLoading.service({ lock: true, text: '数据加载中...' });
            }
            let header = {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            };
            if(tool.cookieValue("XSRF-TOKEN")){
                header["X-XSRF-TOKEN"] = tool.cookieValue("XSRF-TOKEN");
            }
            if(tool.getLoginToken()){
                header["Login-Token"] = tool.getLoginToken();
            }

            axios({
                headers: header,
                url: obj.url,
                method: "POST",
                data: qs.stringify(obj.data)
            }).then(function (response) {
                if(loading){
                    loading.close();
                }
                if (!loginError(response)) {
                    return;
                }
                if (obj.callBack != null) {
                    obj.callBack(response.data);
                }
            }).catch(function (error) {
                if(loading){
                    loading.close();
                }
                if (obj.errCallBack != null) {
                    obj.errCallBack();
                } else {
                    singleObject.singleAlert("请求异常", "错误信息",{
                        confirmButtonText: '确定',
                        type: 'error'
                    });
                }
            });
        }
    };
    w.formRequest = formRequest;

    /**
     * application/json; charset=UTF-8
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩
     */
    const formJsonRequest = function (url, data, errCallBack, callBack, isUseLoading) {
        this.url = url;
        this.data = data;
        this.errCallBack = errCallBack;
        this.callBack = callBack;
        this.isUseLoading = isUseLoading;
        this.init();
    };
    formJsonRequest.prototype = {
        init: function () {
            var obj = this;

            let loading = null;
            if(this.isUseLoading){
                loading = ElLoading.service({ lock: true, text: '数据加载中...' });
            }
            let header = {
                "Content-Type": "application/json; charset=UTF-8"
            };
            if(tool.cookieValue("XSRF-TOKEN")){
                header["X-XSRF-TOKEN"] = tool.cookieValue("XSRF-TOKEN");
            }
            if(tool.getLoginToken()){
                header["Login-Token"] = tool.getLoginToken();
            }
            axios({
                headers: header,
                url: obj.url,
                method: "POST",
                data: obj.data
            }).then(function (response) {
                if(loading){
                    loading.close();
                }
                if (!loginError(response)) {
                    return;
                }
                if (obj.callBack != null) {
                    obj.callBack(response.data);
                }
            }).catch(function (error) {
                if(loading){
                    loading.close();
                }
                if (obj.errCallBack != null) {
                    obj.errCallBack();
                } else {
                    singleObject.singleAlert("请求异常", "错误信息",{
                        confirmButtonText: '确定',
                        type: 'error'
                    });
                }
            });
        }
    };
    w.formJsonRequest = formJsonRequest;

    /**
     * application/json; charset=UTF-8，
     * 返回设置responseType: 'blob'
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩
     */
    const formJsonRequestStream = function (url, data, errCallBack, callBack, isUseLoading) {
        this.url = url;
        this.data = data;
        this.errCallBack = errCallBack;
        this.callBack = callBack;
        this.isUseLoading = isUseLoading;
        this.init();
    };
    formJsonRequestStream.prototype = {
        init: function () {
            var obj = this;

            let loading = null;
            if(this.isUseLoading){
                loading = ElLoading.service({ lock: true, text: '数据加载中...' });
            }
            let header = {
                "Content-Type": "application/json; charset=UTF-8"
            };
            if(tool.cookieValue("XSRF-TOKEN")){
                header["X-XSRF-TOKEN"] = tool.cookieValue("XSRF-TOKEN");
            }
            if(tool.getLoginToken()){
                header["Login-Token"] = tool.getLoginToken();
            }
            axios({
                headers: header,
                url: obj.url,
                method: "POST",
                data: obj.data,
                responseType: 'blob'
            }).then(function (response) {
                if(loading){
                    loading.close();
                }
                if(response.data.type.indexOf("application/json")>= 0){
                    singleObject.singleAlert("获取下载文件失败", "错误信息",{
                        confirmButtonText: '确定',
                        type: 'error'
                    });
                    return;
                }
                if (obj.callBack != null) {
                    obj.callBack(response);
                }
            }).catch(function (error) {
                if(loading){
                    loading.close();
                }
                if (obj.errCallBack != null) {
                    obj.errCallBack();
                } else {
                    singleObject.singleAlert("请求异常", "错误信息",{
                        confirmButtonText: '确定',
                        type: 'error'
                    });
                }
            });
        }
    };
    w.formJsonRequestStream = formJsonRequestStream;

    const htmlOfButton = function (app, callBack) {
        this.url = "/action/permission/buttonListOfHtml";
        this.callBack = callBack;
        this.app = app;
        this.init();
    };
    htmlOfButton.prototype = {
        init: function () {
            var obj = this;
            var param = {
                menuId: this.app.$route.query.menuId
            };
            new formRequest(this.url, param, null, function (data) {
                if (obj.callBack != null) {
                    obj.callBack(data);
                }
            });
        }
    };
    w.htmlOfButton = htmlOfButton;

    const htmlAuthority = function (app, btOption) {
        var obj = app;
        new htmlOfButton(app, function (data) {
            if (data.code === "0000") {
                var result = data.data;
                for (var i = 0; i < result.length; i++) {
                    var item = result[i];
                    var btName = item.btName;
                    if (btName != null && btName != "") {
                        var btValue = obj.btOption[btName];
                        if (typeof (btValue) === "object") {
                            btValue.btDescribe = item.btDescribe;
                            btValue.btName = item.btName;
                            btValue.isAllow = item.isAllow;
                            btValue.requestId = item.requestId;
                            btValue.requestUrl = item.requestUrl;
                        }
                    }
                }
            } else {
                singleObject.singleAlert("请求异常", "错误信息",{
                    confirmButtonText: '确定',
                    type: 'error'
                });
            }
        });
    };
    w.htmlAuthority = htmlAuthority;
})(request);

const tool = new Object();

(function (t) {

    /**
     * 获取cookie的值
     * @param {*} name cookie的名称 
     * @returns cookie的值
     */
    t.cookieValue = function (name) {
        let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return decodeURI(arr[2]);
        else
            return null;
    };

    /**
     * 删除cookie
     * @param name cookie的名称
     */
    t.cookieDelete = function (name) {
        document.cookie = name + "=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    };

    /**
     * get请求
     * @param url 请求的相对路径
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩，未传值代表使用
     */
    t.getRequest = function (url, errCallBack, callBack, isUseLoading) {
        if(typeof(isUseLoading) === "undefined" || isUseLoading == null){
            isUseLoading = true;
        }
        let path = config.requestConfig.httpDomain + config.requestConfig.httpContext + url;
        new request.getRequest(path, errCallBack, callBack, isUseLoading);
    }

    /**
     * application/x-www-form-urlencoded; charset=UTF-8 
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩，未传值代表使用
     */
    t.formRequest = function (url, data, errCallBack, callBack, isUseLoading) {
        if(typeof(isUseLoading) === "undefined" || isUseLoading == null){
            isUseLoading = true;
        }
        let path = config.requestConfig.httpDomain + config.requestConfig.httpContext + url;
        new request.formRequest(path, data, errCallBack, callBack, isUseLoading);
    }

    /**
     * application/json; charset=UTF-8
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩，未传值代表使用
     */
    t.formJsonRequest = function (url, data, errCallBack, callBack, isUseLoading) {
        if(typeof(isUseLoading) === "undefined" || isUseLoading == null){
            isUseLoading = true;
        }
        let path = config.requestConfig.httpDomain + config.requestConfig.httpContext + url;
        new request.formJsonRequest(path, data, errCallBack, callBack, isUseLoading);
    }

    /**
     * application/json; charset=UTF-8,
     * 返回设置responseType: 'blob'
     * @param url 请求的相对路径
     * @param data 请求的数据
     * @param errCallBack 请求异常的回调
     * @param callBack 请求成功的回调
     * @param isUseLoading 是否使用loading遮罩，未传值代表使用
     */
    t.formJsonRequestStream = function (url, data, errCallBack, callBack, isUseLoading) {
        if(typeof(isUseLoading) === "undefined" || isUseLoading == null){
            isUseLoading = true;
        }
        let path = config.requestConfig.httpDomain + config.requestConfig.httpContext + url;
        new request.formJsonRequestStream(path, data, errCallBack, callBack, isUseLoading);
    }

    /**
     * 获取登录的token信息 
     */
    t.getLoginToken = function () {
        return localStorage.getItem("token");;
    }

    /**
     * 获取页面授权按钮信息
     * @param menuList 页面的id
     * @param btOption 页面按钮属性
     * @param callBack 请求成功的回调
     */
    t.getAuthorisedRequest = function (menuList, btOption, callback) {
        const path = config.requestConfig.httpDomain + "/user/request/getAuthorisedRequest";
        const resultOption = new Object();
        new request.formJsonRequest(path, menuList, null, function(data){
            if(data.code == "0000"){
                let result = data.data;
                for(let i=0; i<result.length; i++){
                    let item = result[i];
                    if(item.permissionName != null && item.permissionName != ""){
                        resultOption[item.permissionName] = item;
                    }
                }
                for(let bt in btOption){
                    if(resultOption[bt]){
                        btOption[bt] = true;
                    }
                }
            }else{
                singleObject.singleAlert("获取授权信息失败", "错误信息",{
                    confirmButtonText: '确定',
                    type: 'error'
                });
            }
            if(callback != null){
                callback();
            }
        }, true);
    }

    t.fileTypeToIcon = {
        xls: "far fa-file-excel",
        xlsx: "far fa-file-excel",
        doc: "far fa-file-word",
        docx: "far fa-file-word",
        pdf: "far fa-file-pdf",
        png: "far fa-file-image",
        jpg: "far fa-file-image",
        gif: "far fa-file-image",
        jpeg: "far fa-file-image",
        ico: "far fa-file-image"
    }

    /**
     * 获取当前日期开始时间
     */
    t.getCurDateStart = function(){
        const curDate = new Date();
        const year = curDate.getFullYear();
        const month = curDate.getMonth() + 1 > 9 ? (curDate.getMonth() + 1) : "0" + (curDate.getMonth() + 1);
        const day = curDate.getDate() > 9 ? curDate.getDate(): "0" + curDate.getDate();
        return year + "-" + month + "-" + day + " 00:00:00";
    }

    /**
     * 获取当前日期结束时间
     */
     t.getCurDateEnd = function(){
        const curDate = new Date();
        const year = curDate.getFullYear();
        const month = curDate.getMonth() + 1 > 9 ? (curDate.getMonth() + 1) : "0" + (curDate.getMonth() + 1);
        const day = curDate.getDate() > 9 ? curDate.getDate(): "0" + curDate.getDate();
        return year + "-" + month + "-" + day + " 23:59:59";
    }
})(tool)
export { tool };